import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 创建 RabbitMQConsumer 类，使用 Consumer 消费消息。
 * @Author: LiuZiHao
 * @Date: 2022/5/6 10:31
 */
public class RabbitMqConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMqProducer.getConnection();
        final Channel channel = connection.createChannel();
        channel.basicQos(64); //设置客户端最多接收未被ack的消息数量为64
        //创建消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //打印日志
                System.out.println(String.format("[线程: %s][路由键: %s][消息内容: %s]",
                        Thread.currentThread(), envelope.getRoutingKey(), new String(body)));
                //ack消息已经消费
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        //订阅消费 QUEUE_NAME 队列
        channel.basicConsume(RabbitMqProducer.QUEUE_NAME, consumer);
        try {
            TimeUnit.HOURS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        channel.close();
        connection.close();
    }
}
